(function() {
  app.service('my_zxg_v', function(tradeApi, $q, $window) {
    var that = this;

    this.page = ['/zixuan', '/detail', '/detail_zs', '/search'];
    this.my_zxg = null;

    this.type = null;

    this.updata = function(type) {
      if (type) that.type = type;

      var deferred = $q.defer();

      if (that.type === 'local') {
        that.my_zxg = angular.fromJson(localStorage.getItem('my_zxg')) || [];
        deferred.resolve(that.my_zxg);
      }

      if (that.type === 'http') {
        tradeApi.query({
          funcId: '300032',
          data: {}
        }).then(function(res) {
          that.my_zxg = res || [];
          deferred.resolve(that.my_zxg);
        });
      }
      return deferred.promise;
    };


    this.check = function(obj, checkProp) { // 检测是否该自选已经存在  checkProp为可以识别的唯一性的key键
      var flag = -1;
      var prop = checkProp || 'code'; // 辨识身份的属性
      that.my_zxg
        .some(function(x, index) {
          if (x[prop] === obj[prop]) {
            flag = index;
            return true;
          }
          return false;
        });
      return flag;
    };

    this.del = function(del_obj) {
      var del_index = that.check(del_obj);
      if (del_index === -1) return;
      that.my_zxg.splice(del_index, 1);
    };

    this.add = function(add_obj, add_index) {
      that.my_zxg.splice(add_index || 0, 0, add_obj);
    };

    this.set = function(obj, config) {
      var deferred = $q.defer();
      var copyed = angular.copy(that.my_zxg);

      if (config.del) {
        var exist_flag = that.check(obj);
        if (exist_flag !== -1) copyed.splice(exist_flag, 1);
      }

      if (config.add) {
        copyed.splice(config.add_index || 0, 0, obj);
      }

      if (config.toggle) {
        var exist_flag2 = that.check(obj);
        exist_flag2 !== -1 ? copyed.splice(exist_flag2, 1) : copyed.splice(config.add_index || 0, 0, obj);
      }

      if (that.type === 'local') {
        that.my_zxg = copyed;
        localStorage.setItem('my_zxg', angular.toJson(that.my_zxg));
        deferred.resolve(that.my_zxg);
      }

      if (that.type === 'http') {
        tradeApi
          .query({
            funcId: '300031',
            data: {
              param: copyed
            }
          })
          .then(function(res) {
            that.my_zxg = copyed;
            deferred.resolve(that.my_zxg);
          });
      }
      return deferred.promise;
    };
  });
})();
